package com.hanyizhu.demostore.service.impl;


import com.hanyizhu.demostore.entity.User;
import com.hanyizhu.demostore.mapper.UserMapper;
import com.hanyizhu.demostore.service.IUserService;
import com.hanyizhu.demostore.service.ex.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

@Service //@Service注解:将当前类的对象交给Spring来管理,自动创建对象以及对象管理
/**用户模块业务层的实习类*/
/**
 * @author lenovo
 */
public class
UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        //通过user参数来获取传递过的username
        String username = user.getUsername();
        //调用 findByUsername(Username username)判断用户是否被注册
        User result = userMapper.findByUsername(username);
        //判断结果集是否为null,不为null则抛出用户名被占用的异常
        if(result != null){
            //抛出异常
            throw new UsernameDuplicatedException("用户名被占用");
        }

        //密码加密处理:MD5算法的形式
        //(串+password+串)----md5算法进行加密,连续加载3次
        //盐值+password+盐值 --- 盐值就是一个随机的字符串
        String oldPassword = user.getPassword();
        //获取盐值(随机字符串(盐值))
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值作为一个整个进行加密处理(忽略原有密码的强调提升数据的安全性)
        String md5Password = getMd5Password(oldPassword, salt);
        //将加密之后密码补全设置到user对象中
        user.setPassword(md5Password);

        //补全数据:盐值salt的记录
        user.setSalt(salt);
        //补全数据:is_delete设置成0
        user.setIsDelete(0);
        //补全数据:4个日志信息
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        //执行注册业务逻辑实现
        Integer rows = userMapper.insert(user);
        if (rows !=1 ){
            throw new InserException("在用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据用户名称来查询用户的数据是否存在,不存在则抛异常
        User result = userMapper.findByUsername(username);
        if (result == null){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        //检测用户的密码是否匹配
        //1.先获取到数据库的加密之后的密码
        String oldmd5password = result.getPassword();
        //2.和用户的传递过来的密码进行比较
        //2.1先获取盐值:上一次注册时所自动生成的盐值
        String salt = result.getSalt();
        //2.2将用户的密码按照相同的md5算法的规则进行加密
        String newmd5Password = getMd5Password(password, salt);
        //2.3将密码进行比较
        if (!newmd5Password.equals(oldmd5password)){
            throw new PasswordNotMatchException("密码错误");
        }
        // p判断is_delete字段的值是否为1表示被删除
        if (result.getIsDelete()==1){
            throw new UsernameNotFoundException("用户数据不存在");
        }

        return newContainer(result.getUid());

    }

    @Override
    public void changePassword(Integer uid, String username,String oldPassword,String newPassword) {
        User result = judgeUid(uid);
        //原始密码和数据库密码进行比较
        String oldMd5Password = getMd5Password(oldPassword, result.getSalt());
        if (!result.getPassword().equals(oldMd5Password)){
            throw new PasswordNotMatchException("旧密码错误");
        }
        //将新的密码设置到数据库中
        //1.将新的密码再去更新密码
        String newMd5Password = getMd5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updatePasswordByUid(uid,
                                                      newMd5Password,
                                                      username,
                                                      new Date());
        if (rows !=1){
            throw new InserException("更新数据产生的未知异常");
        }

    }

    @Override
    public User getByUid(Integer uid) {
        judgeUid(uid);
        return newContainer(uid);
    }

    @Override
    public void changeInfo(User user, Integer uid, String username) {
        judgeUid(uid);
        user.setUid(uid);
        user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if (rows != 1){
            throw new UpdateException("更新数据时,产生了未知的错误");
        }
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        //查询当前的用户数据是否存在
        User result = userMapper.findByUid(uid);
        if (result == null || result.getUid() == 1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新时产生的未知异常");
        }
    }

    /**定义一个MD5算法的加密处理*/
    private String getMd5Password(String password, String salt){
        //md5加密算法的方法调用(三次加密)
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex(
                    (salt + password + salt).getBytes()).toUpperCase();

        }
        //返回加密之后的密码
        return password;

    }

    /**
     * 判断用户信息是否存在
     * @param uid 用户id
     * @return 用户对象信息
     */
    private User judgeUid(Integer uid){
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete()==1){
            throw new UsernameNotFoundException("用户数据不存在");
        }
        return result;
    }

    private User newContainer(Integer uid){
        User result = judgeUid(uid);
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPassword(result.getPassword());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        user.setUid(result.getUid());
        user.setAvatar(result.getAvatar());
        return user;
    }



}
